package com.campusbackend.controller;

import com.campusbackend.entity.Result;
import com.campusbackend.entity.Teams;
import com.campusbackend.entity.TeamMembers;
import com.campusbackend.entity.vo.TeamCreateVO;
import com.campusbackend.entity.vo.TeamDetailVO;
import com.campusbackend.entity.vo.TeamUpdateVO;
import com.campusbackend.entity.vo.MemberScoreVO;
import com.campusbackend.entity.vo.TeamListVO;
import com.campusbackend.entity.vo.TeacherTeamsVO;
import com.campusbackend.entity.vo.TeamEditVO;
import com.campusbackend.entity.vo.TeamMembersUpdateVO;
import com.campusbackend.entity.vo.StudentTeamVO;
import com.campusbackend.service.TeamsService;
import com.campusbackend.service.TeamMembersService;
import com.campusbackend.service.TeamExpertsService;
import com.campusbackend.utils.ResultUtil;
import com.campusbackend.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 队伍表 前端控制器
 * </p>
 *
 * @author yezi
 * @since 2025-07-26
 */
@Slf4j
@RestController
@RequestMapping("/teams")
public class TeamsController {

    @Autowired
    private TeamsService teamsService;
    
    @Autowired
    private TeamMembersService teamMembersService;
    
    @Autowired
    private TeamExpertsService teamExpertsService;

    /**
     * 创建队伍
     * @param teamCreateVO 队伍创建信息
     * @return 创建结果
     */
    @PostMapping("/create")
    @Transactional
    public Result<Map<String, Object>> createTeam(@RequestBody TeamCreateVO teamCreateVO) {
        log.info("创建队伍请求 - teamType: {}, members count: {}", 
                teamCreateVO.getTeamType(), teamCreateVO.getMembers().size());
        
        // 获取当前登录教师信息
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Long instructorId = ((Number) userInfo.get("id")).longValue();
        String instructorName = (String) userInfo.get("username");
        
        // 生成队伍编号
        String teamCode = generateTeamCode();
        
        // 生成随机队伍昵称
        String teamName = generateRandomTeamName();
        
        // 创建队伍
        Teams team = new Teams();
        team.setTeamName(teamName); // 使用随机生成的有趣昵称
        team.setTeamCode(teamCode);
        team.setTeamType(teamCreateVO.getTeamType());
        team.setInstructorId(instructorId);
        team.setTeamIntro("");
        team.setCurrentCompetition("");
        team.setAwardInfo("");
        team.setMaxMembers(30);
        team.setCurrentMembers(teamCreateVO.getMembers().size());
        team.setStatus((byte) 1);
        team.setCreateTime(LocalDateTime.now());
        team.setUpdateTime(LocalDateTime.now());
        
        // 保存队伍
        teamsService.save(team);
        
        // 添加队伍成员
        for (TeamCreateVO.TeamMemberVO memberVO : teamCreateVO.getMembers()) {
            TeamMembers member = new TeamMembers();
            member.setTeamId(team.getId());
            member.setStudentId(memberVO.getStudentId());
            member.setMemberRole(memberVO.getMemberRole());
            member.setJoinStatus((byte) 1); // 1-已加入
            member.setJoinTime(LocalDateTime.now());
            member.setCreateTime(LocalDateTime.now());
            member.setUpdateTime(LocalDateTime.now());
            
            teamMembersService.save(member);
        }
        
        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("teamId", team.getId());
        result.put("teamCode", teamCode);
        result.put("teamName", teamName); // 返回生成的队伍名称
        result.put("message", "队伍创建成功");
        
        return ResultUtil.success(result);
    }

    /**
     * 获取队伍详细信息
     * @param teamId 队伍ID
     * @return 队伍详情
     */
    @GetMapping("/{teamId}")
    public Result<TeamDetailVO> getTeamDetail(@PathVariable Long teamId) {
        log.info("获取队伍详情请求 - teamId: {}", teamId);
        
        TeamDetailVO teamDetail = teamsService.getTeamDetail(teamId);
        
        if (teamDetail == null) {
            return ResultUtil.fail("队伍不存在");
        }
        
        return ResultUtil.success(teamDetail);
    }

    /**
     * 获取当前教师的队伍信息
     * @return 教师队伍信息（组建的队伍 + 入驻的队伍）
     */
    @GetMapping("/my-teams")
    public Result<TeacherTeamsVO> getMyTeams() {
        // 获取当前登录教师信息
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Long teacherId = ((Number) userInfo.get("id")).longValue();
        
        log.info("获取教师队伍信息请求 - teacherId: {}", teacherId);
        
        TeacherTeamsVO teacherTeams = teamsService.getTeacherTeams(teacherId);
        
        // 设置教师姓名（从ThreadLocal获取）
        if (teacherTeams.getTeacherName() == null || teacherTeams.getTeacherName().isEmpty()) {
            String teacherName = (String) userInfo.get("username");
            teacherTeams.setTeacherName(teacherName);
        }
        
        return ResultUtil.success(teacherTeams);
    }

    /**
     * 获取所有队伍列表
     * @return 所有队伍列表
     */
    @GetMapping("/all")
    public Result<List<TeamListVO>> getAllTeams() {
        // 获取当前登录教师信息
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Long currentTeacherId = ((Number) userInfo.get("id")).longValue();
        
        log.info("获取所有队伍列表请求 - currentTeacherId: {}", currentTeacherId);
        
        List<TeamListVO> teams = teamsService.getAllTeams(currentTeacherId);
        
        // 调试信息：输出角色关系
        teams.forEach(team -> {
            if (!"".equals(team.getRoleInTeam())) {
                log.info("队伍角色关系 - teamId: {}, teamName: {}, roleInTeam: {}", 
                        team.getTeamId(), team.getTeamName(), team.getRoleInTeam());
            }
        });
        
        return ResultUtil.success(teams);
    }

    /**
     * 教师入驻队伍
     * @param teamId 队伍ID
     * @return 入驻结果
     */
    @PostMapping("/{teamId}/join")
    public Result<String> joinTeam(@PathVariable Long teamId) {
        // 获取当前登录教师信息
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Long expertId = ((Number) userInfo.get("id")).longValue();
        String expertName = (String) userInfo.get("username");
        
        log.info("教师入驻队伍请求 - teacherId: {}, teacherName: {}, teamId: {}", 
                expertId, expertName, teamId);
        
        try {
            boolean success = teamExpertsService.joinTeam(teamId, expertId);
            
            if (success) {
                return ResultUtil.success("入驻队伍成功");
            } else {
                return ResultUtil.fail("入驻队伍失败");
            }
        } catch (RuntimeException e) {
            log.warn("教师入驻队伍失败 - teacherId: {}, teamId: {}, error: {}", 
                    expertId, teamId, e.getMessage());
            return ResultUtil.fail(e.getMessage());
        } catch (Exception e) {
            log.error("教师入驻队伍异常 - teacherId: {}, teamId: {}", expertId, teamId, e);
            return ResultUtil.fail("入驻队伍时发生系统异常");
        }
    }

    /**
     * 获取队伍编辑信息
     * @param teamId 队伍ID
     * @return 队伍编辑信息
     */
    @GetMapping("/{teamId}/edit")
    public Result<TeamEditVO> getTeamEditInfo(@PathVariable Long teamId) {
        // 获取当前登录教师信息
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Long currentTeacherId = ((Number) userInfo.get("id")).longValue();
        
        log.info("获取队伍编辑信息请求 - teamId: {}, teacherId: {}", teamId, currentTeacherId);
        
        TeamEditVO teamEditInfo = teamsService.getTeamEditInfo(teamId);
        
        if (teamEditInfo == null) {
            return ResultUtil.fail("队伍不存在");
        }
        
        // 验证权限：只有指导老师可以编辑队伍
        if (!teamEditInfo.getInstructorId().equals(currentTeacherId)) {
            return ResultUtil.fail("您没有权限编辑此队伍");
        }
        
        return ResultUtil.success(teamEditInfo);
    }

    /**
     * 更新队伍成员
     * @param teamId 队伍ID
     * @param updateVO 更新信息
     * @return 更新结果
     */
    @PutMapping("/{teamId}/members")
    public Result<String> updateTeamMembers(@PathVariable Long teamId, @RequestBody TeamMembersUpdateVO updateVO) {
        // 获取当前登录教师信息
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Long currentTeacherId = ((Number) userInfo.get("id")).longValue();
        
        log.info("更新队伍成员请求 - teamId: {}, teacherId: {}, memberCount: {}", 
                teamId, currentTeacherId, updateVO.getMembers().size());
        
        try {
            // 验证权限：只有指导老师可以更新队伍成员
            TeamEditVO teamInfo = teamsService.getTeamEditInfo(teamId);
            if (teamInfo == null) {
                return ResultUtil.fail("队伍不存在");
            }
            if (!teamInfo.getInstructorId().equals(currentTeacherId)) {
                return ResultUtil.fail("您没有权限管理此队伍");
            }
            
            boolean success = teamsService.updateTeamMembers(teamId, updateVO);
            
            if (success) {
                return ResultUtil.success("队伍成员更新成功");
            } else {
                return ResultUtil.fail("队伍成员更新失败");
            }
        } catch (RuntimeException e) {
            log.warn("更新队伍成员失败 - teamId: {}, teacherId: {}, error: {}", 
                    teamId, currentTeacherId, e.getMessage());
            return ResultUtil.fail(e.getMessage());
        } catch (Exception e) {
            log.error("更新队伍成员异常 - teamId: {}, teacherId: {}", teamId, currentTeacherId, e);
            return ResultUtil.fail("更新队伍成员时发生系统异常");
        }
    }

    /**
     * 搜索队伍
     * @param keyword 搜索关键词（队伍编号或名称）
     * @return 匹配的队伍列表
     */
    @GetMapping("/search")
    public Result<List<TeamListVO>> searchTeams(@RequestParam(required = false) String keyword) {
        // 获取当前登录教师信息
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Long currentTeacherId = ((Number) userInfo.get("id")).longValue();
        
        log.info("搜索队伍请求 - keyword: {}, teacherId: {}", keyword, currentTeacherId);
        
        List<TeamListVO> teams = teamsService.searchTeams(keyword, currentTeacherId);
        
        return ResultUtil.success(teams);
    }

    /**
     * 学生查看自己的所属队伍信息
     * @return 学生队伍信息
     */
    @GetMapping("/my-team")
    public Result<StudentTeamVO> getMyTeam() {
        // 获取当前登录学生信息
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Long studentId = ((Number) userInfo.get("id")).longValue();

        log.info("获取学生队伍信息请求 - studentId: {}", studentId);

        StudentTeamVO studentTeam = teamsService.getStudentTeamInfo(studentId);

        if (studentTeam == null) {
            return ResultUtil.fail("学生信息不存在");
        }

        return ResultUtil.success(studentTeam);
    }

    /**
     * 更新队伍信息
     * @param teamUpdateVO 队伍更新信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public Result<String> updateTeamInfo(@RequestBody TeamUpdateVO teamUpdateVO) {
        log.info("更新队伍信息请求 - teamId: {}, teamName: {}", 
                teamUpdateVO.getTeamId(), teamUpdateVO.getTeamName());
        
        boolean success = teamsService.updateTeamInfo(teamUpdateVO);
        
        if (success) {
            return ResultUtil.success("队伍信息更新成功");
        } else {
            return ResultUtil.fail("队伍信息更新失败");
        }
    }

    /**
     * 队员打分
     * @param memberScoreVO 队员打分信息
     * @return 打分结果
     */
    @PutMapping("/score")
    public Result<String> scoreMember(@RequestBody MemberScoreVO memberScoreVO) {
        log.info("队员打分请求 - teamId: {}, studentId: {}, score: {}", 
                memberScoreVO.getTeamId(), memberScoreVO.getStudentId(), memberScoreVO.getScore());
        
        // 参数验证
        if (memberScoreVO.getScore().compareTo(BigDecimal.ZERO) < 0 || 
            memberScoreVO.getScore().compareTo(new BigDecimal("20")) > 0) {
            return ResultUtil.fail("分数必须在0-20分之间");
        }
        
        boolean success = teamMembersService.updateMemberScore(
                memberScoreVO.getTeamId(), 
                memberScoreVO.getStudentId(), 
                memberScoreVO.getScore()
        );
        
        if (success) {
            return ResultUtil.success("评分成功");
        } else {
            return ResultUtil.fail("评分失败，请确认队伍和学生信息是否正确");
        }
    }
    
    /**
     * 生成队伍编号
     * @return 队伍编号
     */
    private String generateTeamCode() {
        String timestamp = String.valueOf(System.currentTimeMillis()).substring(8);
        String random = String.valueOf((int)(Math.random() * 9000) + 1000);
        return "TEAM" + timestamp + random;
    }
    
    /**
     * 生成随机有趣的队伍昵称
     * @return 队伍昵称
     */
    private String generateRandomTeamName() {
        // 形容词数组
        String[] adjectives = {
            "勇敢的", "智慧的", "闪亮的", "神秘的", "快乐的", "强大的", "敏捷的", "创新的",
            "梦幻的", "超凡的", "无敌的", "传奇的", "精英的", "王者的", "至尊的", "光辉的",
            "炫酷的", "霸气的", "逆天的", "超神的", "完美的", "极致的", "巅峰的", "卓越的",
            "奇迹的", "荣耀的", "辉煌的", "璀璨的", "震撼的", "惊艳的", "绝世的", "非凡的"
        };
        
        // 名词数组
        String[] nouns = {
            "战士", "探索者", "编程者", "创造者", "梦想家", "先锋", "守护者", "建筑师",
            "魔法师", "骑士", "忍者", "猎人", "法师", "游侠", "圣骑士", "剑客",
            "代码侠", "算法王", "数据师", "架构师", "黑客", "极客", "程序猿", "攻城狮",
            "科技星", "创客团", "码农团", "技术控", "开发者", "设计师", "产品经理", "全栈侠"
        };
        
        // 特殊队伍名称（直接使用，不需要组合）
        String[] specialNames = {
            "代码征服者", "算法终结者", "Bug猎手", "键盘侠客", "代码诗人", "数字游侠",
            "网络骑士", "云端战队", "数据风暴", "极客联盟", "创新工坊", "梦想编织者",
            "未来创客", "星际程序员", "量子开发者", "人工智能先锋", "区块链守护者", "元宇宙探索者"
        };
        
        Random random = new Random();
        
        // 30% 概率使用特殊名称，70% 概率使用形容词+名词组合
        if (random.nextInt(10) < 3) {
            return specialNames[random.nextInt(specialNames.length)];
        } else {
            String adjective = adjectives[random.nextInt(adjectives.length)];
            String noun = nouns[random.nextInt(nouns.length)];
            return adjective + noun;
        }
    }
}
